import { RouteLocationNormalizedLoadedGeneric } from 'vue-router'
import { KeepAliveType } from '../types'

export const useKeepAliveStore = defineStore(
    STORE_KEEPALIVE,
    () => {
        const keepAlive = reactive<KeepAliveType>({
            isRefresh: false, // 是否刷新
            keepAliveNames: [], // 需要缓存的路由名称
        })

        // 添加
        const addKeepAlive = (route: RouteLocationNormalizedLoadedGeneric) => {
            const name = route.name as string
            // 是否存在
            if (keepAlive.keepAliveNames.includes(name)) return
            keepAlive.keepAliveNames.push(name)
        }
        // 移除
        const removeKeepAlive = (keepAliveName: string) => {
            keepAlive.keepAliveNames = keepAlive.keepAliveNames.filter((name) => name !== keepAliveName)
        }

        // 刷新
        const setIsRefresh = (bool: boolean) => {
            keepAlive.isRefresh = bool
        }

        const clearKeepAlive = () => {
            keepAlive.keepAliveNames = []
        }

        return { keepAlive, addKeepAlive, removeKeepAlive, setIsRefresh, clearKeepAlive }
    },
    { persist: true },
)
